<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElCard, ElTag, ElButton, ElEmpty, ElInput, ElMessage, ElSelect, ElOption } from 'element-plus'

// 定义参赛选手接口
interface Participant {
  playerId: number
  playerName: string
  score: number | null
  sdistance: number | null
  stimeValue: number | null
  stype: number | null
  // 时间成绩的各个部分
  hours: number | null
  minutes: number | null
  seconds: number | null
  milliseconds: number | null
  sid: number | null // 添加sid字段
}

// 定义props
const props = defineProps({
  eventId: {
    type: Number,
    required: true
  },
  rankId: {
    type: Number,
    required: true
  },
  scheduleId: {
    type: Number,
    required: true
  }
})

// 响应式数据
const participants = ref<Participant[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const currentPage = ref(1)
const pageSize = ref(8) // 每页显示8条数据
const saving = ref(false)
const scoreType = ref<number>(1) // 默认选择距离成绩

// 计算当前页的数据
const paginatedParticipants = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return participants.value.slice(start, end)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(participants.value.length / pageSize.value)
})

// 获取参赛选手列表的方法
const fetchParticipants = async (eventId: number, rankId: number) => {
  try {
    loading.value = true
    error.value = null
    currentPage.value = 1 // 重置到第一页
    
    const token = localStorage.getItem('token')
    const response = await axios.get('http://localhost:8080/score/listByEventAndRank', {
      headers: {
        token: token || ''
      },
      params: {
        eventId: eventId,
        rankId: rankId
      }
    })
    
    if (response.data.success) {
      // 映射返回的数据字段到Participant接口
      participants.value = response.data.scores.map((item: any) => ({
        playerId: item.userId,
        playerName: item.userName,
        score: item.sscore,
        sdistance: item.sdistance,
        stimeValue: item.stimeValue,
        stype: item.stype,
        sid: item.sid, // 保存sid字段
        // 初始化时间部分
        hours: null,
        minutes: null,
        seconds: null,
        milliseconds: null
      })) || []
    } else {
      error.value = '获取参赛选手列表失败'
    }
  } catch (err) {
    console.error('获取参赛选手列表出错:', err)
    error.value = '获取参赛选手列表时发生错误'
  } finally {
    loading.value = false
  }
}

// 格式化时间显示 (sscore字段，单位是秒，需要转换为 H:mm:ss.SS格式)
const formatTimeScore = (seconds: number | null) => {
  if (seconds === null) return '未评分'
  
  // 计算小时、分钟、秒和毫秒
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  const millis = Math.round((seconds - Math.floor(seconds)) * 100)
  
  // 格式化显示
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}.${millis.toString().padStart(2, '0')}`
  } else {
    return `${minutes}:${secs.toString().padStart(2, '0')}.${millis.toString().padStart(2, '0')}`
  }
}

// 根据stype获取成绩显示
const getScoreDisplay = (participant: Participant) => {
  if (participant.stype === 1) {
    // 距离成绩，单位为米（浮点数）
    return participant.sdistance !== null ? `${participant.sdistance.toFixed(3)}米` : '未评分'
  } else if (participant.stype === 2) {
    // 得分成绩，单位是秒，需要转换为 H:mm:ss.SS格式
    return formatTimeScore(participant.score)
  } else if (participant.stype === 3) {
    // 时间成绩，单位为分（浮点数）
    return participant.stimeValue !== null ? `${participant.stimeValue.toFixed(2)}分` : '未评分'
  }
  return '未评分'
}

// 更新选手成绩
const updateScore = (playerId: number, field: string, value: string) => {
  const participant = participants.value.find(p => p.playerId === playerId)
  if (participant) {
    const numValue = parseFloat(value) || null
    switch (field) {
      case 'score':
        participant.score = numValue
        break
      case 'sdistance':
        participant.sdistance = numValue
        break
      case 'stimeValue':
        participant.stimeValue = numValue
        break
    }
  }
}

// 更新时间成绩的各个部分
const updateTimePart = (playerId: number, part: string, value: string) => {
  const participant = participants.value.find(p => p.playerId === playerId)
  if (participant) {
    const numValue = parseInt(value) || null
    switch (part) {
      case 'hours':
        participant.hours = numValue
        break
      case 'minutes':
        participant.minutes = numValue
        break
      case 'seconds':
        participant.seconds = numValue
        break
      case 'milliseconds':
        participant.milliseconds = numValue
        break
    }
    
    // 计算总秒数
    const hours = participant.hours || 0
    const minutes = participant.minutes || 0
    const seconds = participant.seconds || 0
    const milliseconds = participant.milliseconds || 0
    
    participant.score = hours * 3600 + minutes * 60 + seconds + milliseconds / 1000
  }
}

// 保存成绩
const saveScores = async () => {
  try {
    saving.value = true
    const token = localStorage.getItem('token')
    
    // 准备成绩数据
    const scoresData = participants.value.map(participant => ({
      userId: participant.playerId,
      eventId: props.eventId,
      rankId: props.rankId,
      sscore: participant.score,
      sdistance: participant.sdistance,
      stimeValue: participant.stimeValue,
      stype: scoreType.value, // 使用选择的成绩类型
      sid: participant.sid // 添加sid字段
    }))
    
    const response = await axios.put('http://localhost:8080/score/saveScores', scoresData, {
      headers: {
        token: token || '',
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data.success) {
      ElMessage.success('成绩保存成功')
    } else {
      ElMessage.error('成绩保存失败: ' + response.data.message)
    }
  } catch (err) {
    console.error('保存成绩出错:', err)
    ElMessage.error('保存成绩时发生错误')
  } finally {
    saving.value = false
  }
}

// 切换页面
const changePage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 返回成绩管理页面
const goBackToScoreManager = () => {
  const event = new CustomEvent('showGameEvent', {
    detail: { type: 'backToScoreManager' }
  });
  window.dispatchEvent(event);
}

// 改变成绩类型
const changeScoreType = (type: number) => {
  scoreType.value = type
  // 更新所有参赛选手的成绩类型
  participants.value.forEach(participant => {
    participant.stype = type
  })
}

// 组件挂载时获取数据
onMounted(() => {
  if (props.eventId && props.rankId) {
    fetchParticipants(props.eventId, props.rankId)
  }
})

</script>

<template>
  <div class="write-score-container">
    <div class="header">
      <div class="header-left">
        <el-select v-model="scoreType" @change="changeScoreType" placeholder="请选择成绩类型" class="score-type-select">
          <el-option label="距离" :value="1"></el-option>
          <el-option label="时间" :value="2"></el-option>
          <el-option label="得分" :value="3"></el-option>
        </el-select>
        <h2>成绩录入</h2>
      </div>
      <div class="header-buttons">
        <el-button type="primary" @click="saveScores" :loading="saving" class="save-button">保存成绩</el-button>
        <el-button @click="goBackToScoreManager" class="return-button">返回成绩管理</el-button>
      </div>
    </div>
    
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>数据加载中...</p>
    </div>
    
    <div v-else-if="error" class="error">
      <el-empty :description="error" />
      <el-button type="primary" @click="fetchParticipants(props.eventId, props.rankId)">重新加载</el-button>
    </div>
    
    <div v-else>
      <div v-if="participants.length === 0" class="no-participants">
        <el-empty description="暂无参赛选手数据" />
      </div>
      
      <div v-else class="participants-list">
        <div 
          v-for="(participant, index) in paginatedParticipants" 
          :key="participant.playerId"
          class="item-content"
        >
          <div class="player-rank">
            #{{ (currentPage - 1) * pageSize + index + 1 }}
          </div>
          <div class="player-name">
            {{ participant.playerName }}
          </div>
          
          <div class="score-inputs">
            <template v-if="scoreType === 1">
              <!-- 距离成绩输入 -->
              <el-input 
                v-model="participant.sdistance" 
                placeholder="距离"
                @input="updateScore(participant.playerId, 'sdistance', $event)"
                type="number"
                step="0.001"
              />
              <span class="unit">米</span>
            </template>
            
            <template v-else-if="scoreType === 2">
              <!-- 时间成绩输入 -->
              <div class="time-inputs">
                <el-input 
                  v-model="participant.hours" 
                  placeholder="时"
                  @input="updateTimePart(participant.playerId, 'hours', $event)"
                  type="number"
                  class="time-input"
                />
                <span class="time-separator">:</span>
                <el-input 
                  v-model="participant.minutes" 
                  placeholder="分"
                  @input="updateTimePart(participant.playerId, 'minutes', $event)"
                  type="number"
                  class="time-input"
                />
                <span class="time-separator">:</span>
                <el-input 
                  v-model="participant.seconds" 
                  placeholder="秒"
                  @input="updateTimePart(participant.playerId, 'seconds', $event)"
                  type="number"
                  class="time-input"
                />
                <span class="time-separator">.</span>
                <el-input 
                  v-model="participant.milliseconds" 
                  placeholder="毫秒"
                  @input="updateTimePart(participant.playerId, 'milliseconds', $event)"
                  type="number"
                  class="time-input"
                />
                <span class="unit">秒</span>
              </div>
            </template>
            
            <template v-else-if="scoreType === 3">
              <!-- 得分成绩输入 -->
              <el-input 
                v-model="participant.stimeValue" 
                placeholder="得分"
                @input="updateScore(participant.playerId, 'stimeValue', $event)"
                type="number"
                step="0.01"
              />
              <span class="unit">分</span>
            </template>
          </div>
        </div>
      </div>
      
      <!-- 分页控件 -->
      <div class="pagination" v-if="participants.length > 0">
        <el-button 
          :disabled="currentPage === 1" 
          @click="changePage(currentPage - 1)"
          plain
          class="page-button"
        >
          上一页
        </el-button>
        
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        
        <el-button 
          :disabled="currentPage === totalPages" 
          @click="changePage(currentPage + 1)"
          plain
          class="page-button"
        >
          下一页
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.write-score-container {
  width: 100%;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.score-type-select {
  width: 120px;
}

.header h2 {
  color: #31B310;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.save-button, .return-button {
  padding: 12px 24px;
  font-size: 16px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(49, 179, 16, 0.2);
  border-top: 4px solid #31B310;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error {
  text-align: center;
  padding: 20px;
}

.no-participants {
  padding: 50px 0;
}

.participants-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.item-content {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 15px 20px;
  transition: all 0.3s ease;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-content:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.player-rank {
  font-size: 20px;
  font-weight: bold;
  color: #31B310;
  width: 40px;
}

.player-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  flex: 1;
}

.score-inputs {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 200px;
}

.score-inputs .el-input {
  width: 120px;
}

.time-inputs {
  display: flex;
  align-items: center;
  gap: 5px;
}

.time-inputs .time-input {
  width: 60px;
}

.time-separator {
  font-size: 16px;
  font-weight: bold;
}

.unit {
  font-size: 14px;
  color: #606266;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.page-button {
  padding: 10px 20px;
  font-size: 16px;
}

.page-info {
  font-size: 16px;
  color: #606266;
  min-width: 150px;
  text-align: center;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .header-left {
    flex-direction: column;
    gap: 10px;
  }
  
  .header-buttons {
    width: 100%;
    justify-content: center;
  }
  
  .pagination {
    flex-wrap: wrap;
  }
  
  .item-content {
    flex-wrap: wrap;
  }
  
  .score-inputs {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>